import query from '../utils/mysql.mjs'
import dayjs from 'dayjs'

export default defineEventHandler(async event => {
  const data = await readBody(event)
  if (data.name || data.tel) {
    const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
    let sql;
    const values = [
      data.name || '',
      data.tel || '',
      data.lens || '',
      data.frame || '',
      data.righteye || '',
      data.lefteye || '',
      data.distance || '',
      data.price || '',
      data.mark || '',
      now
    ];

    if (data.id) {
      sql = `
        UPDATE customers SET 
          name = ?, 
          tel = ?, 
          lens = ?, 
          frame = ?, 
          righteye = ?, 
          lefteye = ?, 
          distance = ?, 
          price = ?, 
          mark = ?, 
          update_time = ?
        WHERE id = ?`;
      values.push(data.id);
    } else {
      sql = `
        INSERT INTO customers 
        (name, tel, lens, frame, righteye, lefteye, distance, price, mark, update_time) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
    }

    console.log(sql, values)
    const result = await query(sql, values);
    if (result.affectedRows > 0) {
      return { code: 0 }
    } else {
      return { code: -1 }
    }
  } else {
    return { code: -1 }
  }
})